package ru.paswd.marketprice.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_category.view.*
import ru.paswd.marketprice.Application
import ru.paswd.marketprice.R
import ru.paswd.marketprice.data.mappers.ProductMapper
import ru.paswd.marketprice.data.models.ProductCategory
import ru.paswd.marketprice.data.repositories.ProductsRepository
import java.util.*
import java.util.stream.Collectors

class ProductCategoryAdapter(private val context: Context, categories: List<ProductCategory>)
    : RecyclerView.Adapter<ProductCategoryAdapter.ViewHolder>() {
    var categories: List<ProductCategory> = listOf()
        set(value) {
            field = value
            initAdapters()
            notifyDataSetChanged()
        }

    private val adapters = mutableMapOf<UUID, ProductAdapter>()

    init {
        this.categories = categories
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ViewHolder(LayoutInflater.from(parent.context)
                .inflate(R.layout.item_category, parent, false))

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val category = categories[position]
        holder.title.text = category.name
        holder.content.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        holder.content.adapter = adapters[category.id]

        ProductsRepository.requestAll(Application.instance!!.applicationContext!!,
                null, category.name
        ) { success, result ->
            if (success) {
                adapters[category.id]?.products = result?.content
                        ?.stream()
                        ?.map { ProductMapper.fromDto(it) }
                        ?.collect(Collectors.toList())
                        ?: listOf()
            }
        }
    }

    override fun getItemCount() = categories.size

    private fun initAdapters() {
        categories.forEach { c ->
            if (c.id != null && adapters[c.id] == null) {
                adapters[c.id] = ProductAdapter(context, listOf())
            }
        }
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val title = view.productCategoryTitle!!
        val content = view.productCategoryContent!!
    }
}